package sunwul.mall.commoncore.filter;

import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import sunwul.mall.commonbase.constant.AuthConstants;
import sunwul.mall.commoncore.model.SecurityUser;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sunwul
 * @date 2024/12/30 10:12
 * @description token转换过滤器
 */
@Slf4j
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 只负责处理携带token的请求, 然后将认证的用户信息转换出来
     * 未携带token的请求, 交给SpringSecurity资源服务器配置类中的处理器进行处理
     *
     * @see sunwul.mall.commoncore.config.ResourceServerConfig authenticationEntryPoint
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取token, 将token转换为用户信息, 并将用户信息装换为Security框架认识的用户信息对象,
        // 再将此用户信息对象存放到当前资源服务的容器中
        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
        log.info("TokenTranslationFilter - authorization=" + authorization);
        if (StringUtils.hasText(authorization)) {
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            if (StringUtils.hasText(token)) {
                // 处理token续签
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                if (expire < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME) {
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token,
                            AuthConstants.TOKEN_TIME, TimeUnit.SECONDS);
                }

                // 从redis中获取json格式的用户信息, 转换为Security安全框架认证用户对象
                String userInfo = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                SecurityUser securityUser = new JsonMapper().readValue(userInfo, SecurityUser.class);

                // 处理权限
                Set<SimpleGrantedAuthority> authorities = securityUser.getPerms().stream()
                        .map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(securityUser, null, authorities);

                // 将认证用户对象存放到当前模块的上下文中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
